package cn.redsoft.turingapi.plugin;

import java.util.HashSet;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.redsoft.turingapi.exception.WechatException;
import cn.redsoft.turingapi.msg.BaseMsg;
import cn.redsoft.turingapi.request.TuringRequest;
import cn.redsoft.turingapi.request.TuringRequestHttpClientImpl;
import cn.redsoft.turingapi.request.TuringRequestMetaData;
import cn.redsoft.wechatapi.msg.req.RequestMsg;
import cn.redsoft.wechatapi.msg.req.generic.TextRequestMsg;
import cn.redsoft.wechatapi.msg.resp.passivity.PassivityResponseMsg;

public class WechatPlugin {

	private Logger logger = LoggerFactory.getLogger(WechatPlugin.class);

	private WechatBaseMsgResolver resolver = new WechatBaseMsgResolver();
	private WechatMsgConverter converter = new WechatMsgConverter();
	private static Set<Class<? extends RequestMsg>> supportedWechatMsgs = new HashSet<Class<? extends RequestMsg>>();

	{
		supportedWechatMsgs.add(TextRequestMsg.class);
	}

	public PassivityResponseMsg doRequest(RequestMsg msg)
			throws WechatException {
		if (!supportedWechatMsgs.contains(msg.getClass())) {
			throw new WechatException("暂不支持的wechat消息类型:"
					+ msg.getMsgType().getValue() + " .");
		}

		TuringRequestMetaData metaData = this.resolver.resolve(msg);

		TuringRequest request = new TuringRequestHttpClientImpl(metaData);

		BaseMsg baseMsg = request.getResult();
		PassivityResponseMsg passivityResponseMsg = this.converter
				.converte(baseMsg);
		if (passivityResponseMsg != null) {
			this.logger.debug("<==> : {}(TuringMsg)<-->{}(WechatMsg)",
					baseMsg.getClass().getSimpleName(), passivityResponseMsg
							.getClass().getSimpleName());
			return passivityResponseMsg;
		}

		throw new WechatException("消息暂时无法转换:" + baseMsg + " .");
	}
}
